//时间转换功能
function calculateRelativeTime(createTime) {
  const now = new Date(); // 获取当前时间
  const pastDate = new Date(createTime); // 根据传入的时间字符串创建Date对象
  // 计算当前时间与评论时间之间的时间差，单位为毫秒
  const diffInMilliseconds = now - pastDate;
  // 将时间差转换为分钟数
  const diffInMinutes = Math.round(diffInMilliseconds / 60000);
  // 计算时间差的绝对值，确保结果为正数
  const diffInMinutesAbs = Math.abs(diffInMinutes);
  let relativeTime = '';
  if (diffInMinutesAbs < 1) {
    relativeTime = '刚刚';
  } else if (diffInMinutesAbs < 60) {
    relativeTime = `${diffInMinutesAbs}分钟前`;
  } else if (diffInMinutesAbs < 60 * 24) {
    relativeTime = `${Math.floor(diffInMinutesAbs / 60)}小时前`;
  } else if (diffInMinutesAbs < 60 * 24 * 2) {
    // 如果时间差小于两天，显示 "一天前" 或 "两天前"
    relativeTime = `${Math.floor(diffInMinutesAbs / 60 / 24)}天前`;
  } else if (diffInMinutesAbs < 60 * 24 * 30) {
    // 如果时间差小于30天，显示 "十几天前" 或 "二十几天前"
    const days = Math.floor(diffInMinutesAbs / 60 / 24);
    if (days >= 10 && days < 20) {
      relativeTime = '十几天前';
    } else if (days >= 20 && days < 30) {
      relativeTime = '二十几天前';
    } else {
      relativeTime = `${days}天前`;
    }
  } else if (diffInMinutesAbs < 60 * 24 * 30 * 12) {
    // 如果时间差小于12个月，显示 "几个月前"
    const months = Math.floor(diffInMinutesAbs / (60 * 24 * 30));
    relativeTime = `${months}个月前`;
  } else {
    // 如果时间差超过12个月，显示 "几年前"
    const years = Math.floor(diffInMinutesAbs / (60 * 24 * 30 * 12));
    relativeTime = `${years}年前`;
  }
  return relativeTime;
}

Page({
  data: {
    id: '',
    title: '',
    content: '',
    imgUrl: '',
    authorId: '',
    authorName: '',
    createTime: '',
    userPhoto: '',
    show: false, // 初始化点赞状态为未点赞
    dianzant: '', // 已点赞图片地址
    dianzanf: '', // 未点赞图片地址
    showComments: false,
    comments: [], // 存储评论列表
    userAvatar: 'https://img.touxiangwu.com/zb_users/upload/2024/04/202404241713939684430985.jpg',
  },

  onLoad: function (options) {
    const wzId = options.wzId;
    const userId = wx.getStorageSync('id');
    this.setData({
      wzId: wzId
    });
    this.fetchPostData(wzId);
    this.checkIfLiked(wzId, userId);
    this.showCommentWindow();
  },

  fetchPostData: function (wzId) {
    wx.request({
      url: 'http://localhost:8880/shequ/wz/get',
      method: 'GET',
      data: {
        id: wzId
      },
      success: (res) => {
        if (res.data.flag) {
          const postData = res.data.data;
          this.setData({
            title: postData.title,
            content: postData.content,
            imgUrl: postData.imgUrl,
            authorName: postData.authorName,
            createTime: postData.createTime,
            authorId: postData.authorId
          });
          this.fetchAuthorData(this.data.authorId);
          console.log("id:::" + this.data.authorId)
        }
      },
      fail: (err) => {
        console.error('获取帖子数据失败', err);
      }
    });
  },

  fetchAuthorData: function (authorId) {
    wx.request({
      url: 'http://localhost:8880/shequ/wxuser/find',
      method: 'GET',
      data: {
        id: authorId
      },
      success: (res) => {
        if (res.data.flag) {
          const authorData = res.data.data;
          this.setData({
            userPhoto: authorData.userPhoto
          });
        }
      },
      fail: (err) => {
        console.error('获取作者信息失败', err);
      }
    });
  },

  checkIfLiked: function (wzId, userId) {
    console.log("efihegfu" + wzId, userId);
    wx.request({
      url: 'http://localhost:8880/shequ/like/isLiked',
      method: 'GET',
      data: {
        wzId: wzId,
        userId: userId
      },
      success: (res) => {
        console.log("gredgv" + res.data)
        if (res.data) {
          this.setData({
            show: true
          });
          this.fetchLikeIcons();
        } else {
          this.setData({
            show: false
          });
          this.fetchLikeIcons();
        }
      },
      fail: (err) => {
        console.error('检查点赞状态失败', err);
      }
    });
  },

  fetchLikeIcons: function () {
    wx.request({
      url: 'http://localhost:8880/shequ/like/getlikeicons?id=6',
      method: 'GET',
      success: (res) => {
        this.setData({
          dianzant: res.data.dian_zant,
          dianzanf: res.data.dian_zanf
        });
      },
      fail: (err) => {
        console.error('获取点赞图标失败', err);
      }
    });
  },

  handleTap: function (event) {
    const index = event.currentTarget.dataset.index;
    const userId = wx.getStorageSync('id'); // 假设的用户ID
    const wzId = this.data.wzId;
    if (this.data.show) {
      this.cancelLike(userId, wzId, index);
    } else {
      this.likeArticle(userId, wzId, index);
    }
  },

  likeArticle: function (userId, wzId) {
    wx.request({
      url: 'http://localhost:8880/shequ/like/likeArticle',
      method: 'POST',
      data: {
        userId: userId,
        wzId: wzId
      },
      success: (res) => {
        console.log('点赞成功' + userId, wzId);
        this.setData({
          show: true
        });
        this.fetchLikeIcons();

        wx.showToast({
          title: '点赞成功',
          icon: 'success',
          duration: 2000
        });
      },
      fail: (err) => {
        console.error('点赞失败', err);
        wx.showToast({
          title: '点赞失败',
          icon: 'none',
          duration: 2000
        });
      }
    });
  },

  cancelLike: function (userId, wzId) {
    wx.request({
      url: 'http://localhost:8880/shequ/like/cancelLikeArticle',
      method: 'POST',
      data: {
        userId: userId,
        wzId: wzId
      },
      success: (res) => {
        console.log('取消点赞成功' + wzId, userId);
        this.setData({
          show: false
        });
        this.fetchLikeIcons();

        wx.showToast({
          title: '取消点赞成功',
          icon: 'success',
          duration: 2000
        });
      },
      fail: (err) => {
        console.error('取消点赞失败', err);
        wx.showToast({
          title: '取消点赞失败',
          icon: 'none',
          duration: 2000
        });
      }
    });
  },
  inputComment: function (event) {
    const value = event.detail.value;
    this.setData({
      commentInput: value
    });
  },

  //发送评论
  sendComment: function () {
    const that = this; // 保存上下文
    const commentContent = this.data.commentInput;
    // 确保commentContent存在且不为空
    if (!commentContent || !commentContent.trim()) {
      wx.showToast({
        title: '评论不能为空',
        icon: 'none',
        duration: 2000
      });
      return; // 如果评论内容为空，停止发送评论
    }
    const articleId = this.data.wzId;
    const userId = wx.getStorageSync('id');
    console.log("评论用户的id：" + userId);
    wx.request({
      url: 'http://localhost:8880/shequ/pl/add',
      data: {
        content: commentContent,
        userId: userId,
        articleId: articleId
      },
      method: 'POST',
      success: function (res) {
        console.log('评论发送成功:' + commentContent);
        // 清除发送框信息
        that.setData({
          commentInput: '' // 将发送框内容置空
        });
        // 发送成功提示
        wx.showToast({
          title: '评论成功',
          icon: 'success',
          duration: 2000
        });
        // 重新加载评论列表
        that.showCommentWindow();
      },
      fail: function (err) {
        console.error('发送评论失败:', err);

        // 发送失败提示
        wx.showToast({
          title: '评论失败，请重试',
          icon: 'none',
          duration: 2000
        });
      }
    });
  },

  showCommentWindow: function () {
    const that = this;
    const articleId = this.data.wzId;

    wx.request({
      url: 'http://localhost:8880/shequ/pl/article/' + articleId,
      method: 'GET',
      success: (res) => {
        const comments = res.data;
        const promises = comments.map(comment => {
          return that.getUserInfo(comment.userId);
        });

        Promise.all(promises)
          .then(usersInfo => {
            // 将用户信息与评论列表合并
            const commentsWithUserInfo = comments.map((comment, index) => ({
              ...comment,
              commentUserPhoto: usersInfo[index].userPhoto ,// 使用新的字段名
              commentUserName:usersInfo[index].userName
            }));

            that.setData({
              showComments: true,
              comments: commentsWithUserInfo.map(comment => ({
                ...comment,
                relativeTime: calculateRelativeTime(comment.createTime) // 添加相对时间字段
              }))
            });
          })
          .catch(err => {
            console.error('为评论检索用户信息失败:', err);
          });
      },
      fail: (err) => {
        console.error('检索评论失败:', err);
      }
    });
  },

  // 获取用户信息的函数
  getUserInfo: function (userId) {
    const that = this;
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'http://localhost:8880/shequ/wxuser/find',
        data: {
          id: userId
        },
        method: 'GET',
        success: (res) => {
          if (res.data.flag) {
            resolve(res.data.data);
          } else {
            reject(new Error('Failed to get user info'));
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  },

});